package com.xiaohui.redis.util;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheUtil<K, V> {

    /**
     * 是否开启本地缓存
     */
    @Value("${cache.switch}")
    private Boolean switchCache;

    /**
     * 初始话缓存
     */
    private Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(30, TimeUnit.SECONDS)
            .build();
    // 结果
    private Map<K, V> resultMap = new HashMap<>();

    public Map<K, V> getResult(List<K> skuIdList, String cachePrefix, Class<V> clazz, Function<List<K>, Map<K, V>> function) {
        if (skuIdList.isEmpty()) {
            return resultMap;
        }
        if (!switchCache) {
            return function.apply(skuIdList);
        }
        // 不在缓存中的集合
        List<K> noCacheList = new ArrayList<>();
        for (K id : skuIdList) {
            String key = cachePrefix + id;
            String content = localCache.getIfPresent(key);
            if (StringUtils.isNotBlank(content)) {
                resultMap.put(id, JSON.parseObject(content, clazz));
            } else {
                noCacheList.add(id);
            }
        }
        if (noCacheList.isEmpty()) {
            return resultMap;
        }
        // 查询数据库
        Map<K, V> noCacheMap = function.apply(noCacheList);
        if (noCacheMap == null) {
            return resultMap;
        }
        // 放入缓存
        for (Map.Entry<K, V> entry : noCacheMap.entrySet()) {
            K k = entry.getKey();
            V v = entry.getValue();
            String key = cachePrefix + k;
            localCache.put(key, JSON.toJSONString(v));
        }
        // 返回结果
        return resultMap;
    }
}
